/**
 * Title: BlockStreamBody.java
 * Description:
 * Copyright: Copyright (c) 2008
 * Company:深圳彩讯科技有限公司
 * Author 罗旭东 (hi@luoxudong.com)
 * Date 2013-9-29 下午4:40:24
 * Version 1.0
 */
package com.luoxudong.phonenumber.service.net.http.filetransfer.manager;

import java.io.File;
import java.io.OutputStream;

import com.luoxudong.phonenumber.service.net.http.asynchttp.UploadHttpResponseHandler;
import com.luoxudong.phonenumber.service.net.http.mime.content.AbstractContentBody;

/** 
 * ClassName: BlockStreamBody
 * Description:重写ContentBody，使其支持分块上传
 * Create by 罗旭东
 * Date 2013-9-29 下午4:40:24
 */
public class BlockStreamBody extends AbstractContentBody {
	/**
	 * 上传的文件
	 */
	private File file = null;
	
	/**
	 * 偏移量
	 */
	private long startOffset = 0;
	
	/**
	 * 文件总大小
	 */
	private long totalSize = 0;
	
	private long blockSize = -1;
	
	private UploadHttpResponseHandler uploadHttpResponseHandler = null;
	
	public BlockStreamBody(String mimeType) {
		super(mimeType);
	}
	
	public BlockStreamBody(UploadHttpResponseHandler uploadHttpResponseHandler, File file, long startOffset, long blockSize)
	{
		this("application/octet-stream");
		this.file = file;
		this.startOffset = startOffset;
		totalSize = file.length();
		this.uploadHttpResponseHandler = uploadHttpResponseHandler;
		this.blockSize = blockSize;
	}

	@Override
	public String getFilename() {
		if (file != null)
		{
			String fileName = file.getName();
			return fileName;
		}
		
		return null;
	}

	@Override
	public void writeTo(OutputStream out) {
		if (uploadHttpResponseHandler != null)
		{
			uploadHttpResponseHandler.writeTo(out, file, startOffset, blockSize);
		}
	}

	@Override
	public String getCharset() {
		return "UTF-8";
	}

	@Override
	public String getTransferEncoding() {
		return "binary";
	}
	@Override
	public long getContentLength() {
		if (blockSize == -1)
		{
			return totalSize - startOffset;
		}
		return blockSize;
	}
}
